package auctionhaus
import grails.converters.JSON

class ListingService {
    def jmsService

    def createListing(Listing l) {
        if (l.save(flush: true)) {
            return l
        }
        else
        {
            return "Unsuccessfull"
        }
    }
    
    def placeBid(Bid b) {
        def msg = ''
        def bid = null;
        def hasErrors = false
        if (b.listing.isClosed)
        {
            hasErrors = true;
            msg = "Bid is closed."
        }
        else if (b.save(flush: true)) {
            bid = b;
            msg = "Bid successfully placed."
        }
        else
        {
            hasErrors = true;
            if (b.errors.fieldErrors.get(0).code == 'increasetoosmall')
            {
                msg =   "Bid must be at least 50 cents greater than current bid."
            }
            else if (b.errors.fieldErrors.get(0).code == 'firstbidtoosmall')
            {
                msg =   "Bid must be at least 50 cents greater than starting bid."
            }
         }
         return [hasErrors: hasErrors, message: msg, bid : bid]

    }

    def closeListing(Listing l) {
        if (l.bids.size() > 0) {
            def bids = Bid.forListing(l).list(sort: 'amount', order: 'desc')
            def numberOfBids = bids.size() 
            def bidWinner = bids.first().bidder
            def winningAmount = bids.first().amount
            l.winner = bidWinner
            l.isClosed = true
            if (l.save(flush: true)) {
                def listingMAP = [name: l.name, description: l.description, seller: l.seller.emailAddress, winner: bidWinner.emailAddress,
                                  startingBid: l.startingBidAmount, winningBidAmount: winningAmount, numberOfBids: numberOfBids,
                                  listingDetail: "http://localhost:8080/AuctionHaus/listing/show/" + l.id, subject: "Congratulations from AuctionHaus"]

                def json = listingMAP as JSON
                jmsService.send(service: "notification", json.toString());
            }
        }
        if (l.bids.size() == 0) {
            l.isClosed = true
            if (l.save(flush: true)) {
                def listingMAP = [name: l.name, description: l.description, seller: l.seller.emailAddress, winner: '',
                        startingBid: l.startingBidAmount, winningBidAmount: "No Winning Bid Amount", numberOfBids: '0',
                        listingDetail: "http://localhost:8080/AuctionHaus/listing/show/" + l.id, subject: "Listing Closed"]

                def json = listingMAP as JSON
                jmsService.send(service: "notification", json.toString());
            }
        }
        return "closedListing"
    }
}
